package com.kyxx.topics.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.StringUtil;
import com.kyxx.topics.utils.TextUtil;
import com.kyxx.topics.utils.Tools;
import com.kyxx.topics.view.MyCommonTitle;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cz.msebera.android.httpclient.Header;

public class UserLoginActivity2 extends Activity implements View.OnClickListener, Callback, PlatformActionListener {

    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR = 3;
    private static final int MSG_AUTH_COMPLETE = 4;
    private MyCommonTitle myCommonTitle;
    private RequestParams params;
    private EditText edUsername, edPassword, edCode;
    private TextView btn_login, btn_register, btn_forgetPwd, btnSendCode, btnLoginType;
    private RelativeLayout layoutUserCode;
    private String userMobile, password, code, token;
    private TextView btn_qq, btn_wx;
    private int thirdLogin = 0, loginType = 1, type, i, j;
    private Handler mHandler;
    private String openId, nickname, avatar;
    private JSONObject jsonObject, jsonObject1;
    private static String APPKEY = "1835003f02938";
    private static String APPSECRET = "f608d269bbd4c9cb4f9b21ac810001cd";
//    private static String APPKEY = "1770c6f012dda";
//    private static String APPSECRET = "8196301ef118a8d76c717c190c51ecfa";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_login2);

        // 初始化短信验证
        SMSSDK.initSDK(this, APPKEY, APPSECRET);
        EventHandler eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eh);

        mHandler = new Handler(this.getMainLooper(), this);
        ShareSDK.initSDK(this);

        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        myCommonTitle = (MyCommonTitle) findViewById(R.id.aci_myTitle);
        myCommonTitle.setTitle("快速登录/注册");
        edUsername = (EditText) findViewById(R.id.ed_username);// 用户名
        layoutUserCode = (RelativeLayout) findViewById(R.id.layout_user_code);
        edCode = (EditText) findViewById(R.id.ed_code);// 验证码
        btnSendCode = (TextView) findViewById(R.id.btn_send_code);// 发送验证码
        btnLoginType = (TextView) findViewById(R.id.btn_login_type);// 登录方式
        edPassword = (EditText) findViewById(R.id.ed_password);// 密码
        btn_login = (TextView) findViewById(R.id.btn_login);// 登录
        btn_register = (TextView) findViewById(R.id.btn_register);// 注册
//        btn_forgetPwd = (TextView) findViewById(R.id.btn_forget_pwd);// 忘记密码

        btn_qq = (TextView) findViewById(R.id.btn_QQ);// QQ登录
        btn_wx = (TextView) findViewById(R.id.btn_WX);// 威信登录

        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (edUsername.getText().toString().length() > 0) {
                    btnSendCode.setBackgroundResource(R.drawable.bg_circle_bule);
                    btnSendCode.setOnClickListener(UserLoginActivity2.this);
                }
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        };
        edUsername.addTextChangedListener(watcher);

        btn_login.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        btnLoginType.setOnClickListener(this);
        btn_qq.setOnClickListener(this);
        btn_wx.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        userMobile = edUsername.getText().toString().trim();
        password = edPassword.getText().toString().trim();
        code = edCode.getText().toString().trim();
        switch (view.getId()) {
            case R.id.btn_send_code:
                if (!TextUtil.isMobile(userMobile)) {
                    Tools.toast(UserLoginActivity2.this, "手机号码格式不正确！");
                    return;
                }
                /* 发送手机验证码 */
                btnSendCode.setOnClickListener(null);
                new MyCount(60000, 1000).start();// 一分钟倒计时
                SMSSDK.getVerificationCode("86", userMobile);
                break;
            case R.id.btn_register:// 跳转注册界面
                startActivity(new Intent(UserLoginActivity2.this, UserRegisterActivity.class).putExtra("type", "register"));
                finish();
                break;
//            case R.id.btn_forget_pwd:// 跳转忘记密码界面
//                startActivity(new Intent(UserLoginActivity2.this, UserRegisterActivity.class).putExtra("type", "forget_pwd"));
//                finish();
//                break;
            case R.id.btn_login_type:// 跳转忘记密码界面
                if (btnLoginType.getText().toString().trim().equals("使用密码登录")) {
                    loginType = 2;
                    btnLoginType.setText("使用验证码登录");
                    edPassword.setVisibility(View.VISIBLE);
                    layoutUserCode.setVisibility(View.GONE);
                } else {
                    btnLoginType.setText("使用密码登录");
                    loginType = 1;
                    edPassword.setVisibility(View.GONE);
                    layoutUserCode.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.btn_login:
                if (StringUtil.isEmpty(userMobile)) {
                    Tools.toast(UserLoginActivity2.this, "手机号码不能为空！");
                    return;
                }
                if (loginType == 2) {
                    if (StringUtil.isEmpty(password)) {
                        Tools.toast(UserLoginActivity2.this, "密码不能为空！");
                        return;
                    }
                    submitData();
                } else if (loginType == 1) {
                    if (!TextUtil.isCode(code, 4)) {
                        Tools.toast(UserLoginActivity2.this, "验证码格式不对！");
                        return;
                    }
                    SMSSDK.submitVerificationCode("86", userMobile, code);
                }
                break;
            case R.id.btn_QQ:
                type = 1;
                thirdLogin = 1;
                Platform qq = ShareSDK.getPlatform(this, QQ.NAME);
                qq.setPlatformActionListener(this);
                qq.SSOSetting(false);
                qq.authorize();
                break;
            case R.id.btn_WX:
                type = 2;
                thirdLogin = 1;
                Platform weixin = ShareSDK.getPlatform(this, Wechat.NAME);
                weixin.setPlatformActionListener(this);
                weixin.SSOSetting(false);
                weixin.authorize();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (thirdLogin == 1) {
//            MyRequestDailog.showDialog(this, "");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        MyRequestDailog.closeDialog();
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
        Message msg = new Message();
        msg.what = MSG_AUTH_COMPLETE;
        msg.obj = platform;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onError(Platform platform, int action, Throwable t) {
        mHandler.sendEmptyMessage(MSG_AUTH_ERROR);
    }

    @Override
    public void onCancel(Platform platform, int action) {
        mHandler.sendEmptyMessage(MSG_AUTH_CANCEL);
    }

    @Override
    public boolean handleMessage(Message msg) {
        thirdLogin = 0;
        switch (msg.what) {
            case MSG_AUTH_CANCEL: {
                // 取消授权
//                MyRequestDailog.closeDialog();
                Tools.toast(this, "取消登录");
            }
            break;
            case MSG_AUTH_ERROR: {
                // 授权失败
//                MyRequestDailog.closeDialog();
                Tools.toast(this, "登录失败");
            }
            break;
            case MSG_AUTH_COMPLETE: {
                // 授权成功
//                Tools.toast(this, "登录成功");
                Platform platform = (Platform) msg.obj;
                // String icon = platform.getDb().getUserIcon();
                if (type == 1) {
                    openId = platform.getDb().getUserId();  // D558B7DE74E0203EB7810652D9B476CE
                    nickname = platform.getDb().getUserName();//栀薇花
                    avatar = platform.getDb().getUserIcon();//http://q.qlogo.cn/qqapp/1105645339/D558B7DE74E0203EB7810652D9B476CE/40
                } else if (type == 2) {
                    openId = platform.getDb().getUserId();
                    nickname = platform.getDb().getUserName();
                    avatar = platform.getDb().getUserIcon();
                }
                // String gender = platform.getDb().getUserGender();
                checkPhone(type);
//              threeLogin(type);// 第三方登录
            }
            break;
        }
        return false;
    }

    /**
     * 第三方登录,授权成功后检测用户知否绑定过手机,没有跳转绑定   D558B7DE74E0203EB7810652D9B476CE
     *
     * @param type //type为区分是绑定还是换绑,  threeType区分是QQ还是WX
     */
    private void checkPhone(final int type) {
        RequestParams params = new RequestParams();
        if (type == 1) {
            params.put("qq", openId);
        } else if (type == 2) {
            params.put("weixin", openId);
        }
        RestClient.post(UrlUtils.CHECKPHONE, params, UserLoginActivity2.this, new ResponseListener(UserLoginActivity2.this, true) {
                    @Override
                    public void success(int arg0, Header[] arg1, org.json.JSONObject jsonObject) {
//                "code": 0,
//                "msg": "手机已经绑定"
//                         "data": {
//                                  "uid": "4",    "nickname": "chen123",    "sex": "0",     "birthday": "0000-00-00",      "qq": "",   "score": "20",
//                                  "login": "10",    "reg_ip": "2072312874",    "reg_time": "1475734136",    "last_login_ip": "2072312874",
//                                  "last_login_time": "1476090248",     "status": "1",   "cover_id": "9",     "thumb": "/Uploads/2016-10-10/57fb59f04a745.jpg"
                        try {
                            if (jsonObject.getInt("code") == 0) {
                                int code = jsonObject.getInt("code");
                                String uid = jsonObject.getJSONObject("data").getString("uid");
                                BaseApp.getModel().setId(uid);
                                String nickname = jsonObject.getJSONObject("data").getString("nickname");
                                BaseApp.getModel().setNickname(nickname);
                                String avatar = jsonObject.getJSONObject("data").getString("thumb");
                                BaseApp.getModel().setAvatar(UrlUtils.APIHTTP + avatar);
                                String mobile = jsonObject.getJSONObject("data").getString("mobile");
                                BaseApp.getModel().setMobile(mobile);
                                finish();
                            } else {
                                startActivityForResult(new Intent(UserLoginActivity2.this, UserBindMobile.class)
                                        .putExtra("avatar", avatar).putExtra("type", 1).putExtra("threeType", type).putExtra("openId", openId).putExtra("nickname", nickname), 0);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int arg0, Header[] arg1, org.json.JSONObject jsonObject) {
                        super.failed(arg0, arg1, jsonObject);
                        try {
                            if (jsonObject.getInt("code") == 0) {
                                int code = jsonObject.getInt("code");
                                String uid = jsonObject.getJSONObject("data").getString("uid");
                                BaseApp.getModel().setId(uid);
                                String nickname = jsonObject.getJSONObject("data").getString("nickname");
                                BaseApp.getModel().setNickname(nickname);
                                String avatar = jsonObject.getJSONObject("data").getString("thumb");
                                BaseApp.getModel().setAvatar(UrlUtils.APIHTTP + avatar);
                                String mobile = jsonObject.getJSONObject("data").getString("mobile");
                                BaseApp.getModel().setMobile(mobile);
                                finish();
                            } else {
                                startActivityForResult(new Intent(UserLoginActivity2.this, UserBindMobile.class)
                                        .putExtra("avatar", avatar).putExtra("type", 1).putExtra("threeType", type).putExtra("openId", openId).putExtra("nickname", nickname), 0);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
        );

    }

    /**
     * 第三方登陆,如果返回201未注册,先注册,注册成功后再登录
     * 登录成功后返回用户信息{"data":{"addtime":"1465699131","guid":
     * "A994A589C315C7CF44DB9C60D7C3AB1E","id":"47","nickname":"咖啡正浓",
     * "pwd":"11762fc9f747003d488defc5b050eabd","username":
     * "781465699131"},"status":200}
     */

    private void threeLogin(final int type) {
//        jsonObject = new JSONObject();
//        jsonObject.put("Password", "");
//        jsonObject.put("LoginName", userid);
//        jsonObject.put("Mode", type);
//        StringEntity s = null;
//        try {
//            s = new StringEntity(jsonObject.toString(), "utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        RequestParams params = new RequestParams();
        params.put("openid", openId);
        if (type == 1) {
            params.put("type", "oauth_qq_id");
        } else if (type == 2) {
            params.put("type", "oauth_wx_id");
        }
        RestClient.post(UrlUtils.THREELOGIN, params, UserLoginActivity2.this, new ResponseListener(UserLoginActivity2.this, true) {


            @Override
            public void success(int arg0, Header[] arg1, org.json.JSONObject result) {

            }

            @Override
            public void failed(int arg0, Header[] arg1, org.json.JSONObject result) {
                super.failed(arg0, arg1, result);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 47) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            Log.e("result", "result=" + result);
            Log.e("event", "event=" + event);
            if (result == SMSSDK.RESULT_COMPLETE) {
                // 短信注册成功后，返回MainActivity,然后提示新好友
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
                    Tools.toast(UserLoginActivity2.this, "提交验证码成功");
                    submitData();
//                    if (type.equals("register")) {
//                        registerNewUser();
//                    } else if (type.equals("forget_pwd")) {
//                        resetPassWord();
//                    }
                    // uu_password.setFocusable(true);
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    Tools.toast(UserLoginActivity2.this, "验证码已经发送");
                }
            } else {
//                MyRequestDailog.closeDialog();
                ((Throwable) data).printStackTrace();
                // int resId = getStringRes(UserRegisterActivity.this,
                // "smssdk_network_error");
                Tools.toast(UserLoginActivity2.this,
                        event == SMSSDK.EVENT_GET_VERIFICATION_CODE ? "验证码频繁，请稍后再试！" : "验证码错误");
                // if (resId > 0) {
                // Tools.toast(UserRegisterActivity.this, resId + "");
                // }
            }
        }
    };

    /**
     * 正常注册后登录 提交信息，调用登录接口 "id": "15", "username": "", "pwd":
     * "e3ceb5881a0a1fdaad01296d7554868d", "mobile": "18660992783", "addtime":
     * "1463471681", "nickname": "", "avatar": ""
     */
    private void submitData() {
        RequestParams params = new RequestParams();
        params.put("mobile", userMobile);
        if (loginType == 2) {
            params.put("Password", password);
        }
        RestClient.post(loginType == 1 ? UrlUtils.LOGINFORCODE : UrlUtils.LOGINFORPSW, params, UserLoginActivity2.this, new ResponseListener(UserLoginActivity2.this, true) {

            @Override
            public void success(int arg0, Header[] arg1, org.json.JSONObject jsonObject) {
                Tools.toast(UserLoginActivity2.this, "登陆成功！");
                finish();
                try {
                    String id = jsonObject.getJSONObject("data").getString("uid");
                    BaseApp.getModel().setId(jsonObject.getJSONObject("data").getString("uid"));
                    String nickName = jsonObject.getJSONObject("data").getString("nickname");
                    BaseApp.getModel().setNickname(jsonObject.getJSONObject("data").getString("nickname"));
                    String mobile = jsonObject.getJSONObject("data").getString("mobile");
                    BaseApp.getModel().setMobile(jsonObject.getJSONObject("data").getString("mobile"));
                    if (Integer.parseInt(jsonObject.getJSONObject("data").getString("cover_id")) > 0) {//头像
                        String avatar = UrlUtils.APIHTTP + jsonObject.getJSONObject("data").getString("thumb");
                        BaseApp.getModel().setAvatar(UrlUtils.APIHTTP + jsonObject.getJSONObject("data").getString("thumb"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(int arg0, Header[] arg1, org.json.JSONObject result) {
                super.failed(arg0, arg1, result);
                Tools.toast(UserLoginActivity2.this, "登陆失败！");
            }
        });

    }

    /* 定义一个倒计时的内部类 */
    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            btnSendCode.setText("获取验证码");
            btnSendCode.setOnClickListener(UserLoginActivity2.this);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btnSendCode.setText(millisUntilFinished / 1000 + "秒");
        }
    }
}
